/*!
 * BottleCMS-UI v1.2.7 (http://ui.bottlecms.com)
 * Copyright 2014-2018 BottleCMS, Inc.
 * Licensed MIT 
 */



/**
 * jQuery plugin "Swipe slider".
 * Image slider that supports swiping function to change slides.
 * sliderHeight '60%'   设置幻灯片的高度。如果你想根据宽度来自动改变高度，可以设置为百分比。如果设置为像素则使用固定高度。
 * transitionDuration  500 幻灯片动画的持续时间，单位毫秒。
 * timingFunction  'ease-out'  过渡动画的easing效果（CSS easing函数）。
 * autoPlay    true    是否自动播放幻灯片。
 * autoPlayTimeout 3000    自动播放的时间间隔，单位毫秒。
 * prevNextButtons true    是否显示前后导航按钮。
 * bullets true    是否显示分页导航按钮。
 * swipe   true    是否允许移动端的swipe事件。
 */
!function(n){n.fn.swipeslider=function(i){function t(){q=B.width(),p()}function e(n){A&&(l(),n.originalEvent.touches&&(n=n.originalEvent.touches[0]),0==H&&(H=1,M=n.clientX))}function o(n){var i;i=n.originalEvent.touches?n.originalEvent.touches[0]:n;var t=i.clientX-M;if(1==H&&0!=t&&(H=2,N=z*-q),2==H){n.preventDefault();var e=1;(0==z&&i.clientX>M||z==Q-1&&i.clientX<M)&&(e=3),j=N+t/e,T(!1),x(j)}}function s(n){2==H&&(H=0,z=N>j?z+1:z-1,z=Math.min(Math.max(z,0),Q-1),j=z*-q,u(),p(),a()),H=0}function u(){A=!1,window.setTimeout(c,G)}function c(){A=!0}function l(){L=!1,window.clearTimeout(K)}function a(){O&&(L=!0,f())}function f(){L&&(K=window.setTimeout(r,J))}function r(){d(),f()}function d(){z+=1,p()}function w(){z-=1,p()}function p(){T(!0),x(-z*q),0==z?window.setTimeout(m,G):z==Q-1&&window.setTimeout(v,G),k(z)}function v(){h(1)}function m(){h(Q-2)}function h(n){T(!1),z=n,x(-q*z),window.setTimeout(g,50)}function g(){T(!0)}function T(n){X(n?"all":"none")}function x(n){B.css("transform","translateX("+n+"px)")}function y(n){B.css("transition-duration",n+"ms")}function b(n){B.css("transition-timing-function",n)}function X(n){B.css("transition-property",n)}function E(){B.after('<span class="sw-next-prev sw-prev"></span>'),D.find(".sw-prev").click(function(){L&&(l(),w(),a())}),B.after('<span class="sw-next-prev sw-next"></span>'),D.find(".sw-next").click(function(){L&&(l(),d(),a())})}function P(n){B.after('<ul class="sw-bullet"></ul>');for(var i=B.parent().find(".sw-bullet"),t=0;n>t;t++){0==t?i.append('<li class="sw-slide-'+t+' active"></li>'):i.append('<li class="sw-slide-'+t+'"></li>');var e=D.find(".sw-slide-"+t);!function(n){e.click(function(){l(),z=n+1,p(),a()})}(t)}}function k(n){var i=0;i=0==n?Q-3:n==Q-1?0:n-1,D.find(".sw-bullet").find("li").removeClass("active"),D.find(".sw-slide-"+i).addClass("active")}var D=this,B=this.find(".sw-slides"),C={transitionDuration:500,autoPlay:!0,autoPlayTimeout:4e3,timingFunction:"ease-out",prevNextButtons:!0,bullets:!0,swipe:!0,sliderHeight:"60%"},F=n.extend(C,i),H=0,M=0,N=0,j=0,z=0,Q=0,q=0,A=!0,G=F.transitionDuration,I=F.swipe,J=F.autoPlayTimeout,K=void 0,L=!0,O=F.autoPlay;return function(){n(D).css("padding-top",F.sliderHeight),q=B.width(),n(window).resize(t),F.prevNextButtons&&E(),B.find(".sw-slide:last-child").clone().prependTo(B),B.find(".sw-slide:nth-child(2)").clone().appendTo(B),Q=B.find(".sw-slide").length,F.bullets&&P(Q-2),y(G),b(F.timingFunction),X("all"),I&&(B.on("mousedown touchstart",e),n("html").on("mouseup touchend",s),n("html").on("mousemove touchmove",o)),h(1),a()}(),D}}(jQuery);


/**
 * 框架初始化
 */
var $$ = bottlecms = [];
/**
 * 自定义parseInt函数
 */
bottlecms.parseInt = function(m, n) {
    try {
        m = '' + m;
        while (m.indexOf('0') === 0) {
            m = m.substr(1);
        }
        if (m == '') {
            return 0;
        }
        var jg = window.parseInt(m, n);
        if (jg + '' == 'NaN') {
            return 0;
        }
        return jg;
    } catch (err) {
        return m;
    }
};
/**
 * 去除两段空格
 */
bottlecms.trim = function(str) {
    try {
        str = str ? str.replace(/(^\s*)|(\s*$)/g, '') : false;
        return str == 'undefined' || str == "" || str == null || str == "null" || str == undefined ? false : str;
    } catch (err) {
        return str;
    }
};
/**
 * cookie
 */
bottlecms.cookie = function(key, value, options) {
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({
            path: '/',
            expires: (new Date((new Date()).getTime() + 1000 * 60 * 60 * 24))
        }, options);
        if (value === null || value === undefined) {
            options.expires = -1;
        }
        if (typeof options.expires === 'number') {
            var minute = options.expires,
                t = options.expires = new Date();
            t.setMinutes(t.getMinutes()  + minute)
        }
        value = String(value);
        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : bottlecms.cookie_encode(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '',
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }
    options = value || {};
    var result, decode = options.raw ? function(s) {
        return s;
    } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
bottlecms.cookie_encode = function(string) {
    var decoded = encodeURIComponent(string);
    var ns = decoded.replace(/(%7B|%7D|%3A|%22|%23|%5B|%5D)/g, function(charater) {
        return decodeURIComponent(charater);
    });
    return ns;
}
/**
 * 打印日志 
 */
bottlecms.log = function(msg) {
    if (window.console && window.console.log) {
        window.console.log(msg);
    }
}

function errlog(err) {
    if (window.console && window.console.log) {
        window.console.log("errlog:" + err);
    }
}
/*
 *本地储存localStorage
 */
bottlecms.localStorage = {
    isLS: window.localStorage ? true : false,
    set: function(key, value) {
        if (this.isLS) window.localStorage.setItem(key, value);
    },
    get: function(key) {
        if (this.isLS) return window.localStorage.getItem(key);
    },
    remove: function(key) {
        if (this.isLS) window.localStorage.removeItem(key);
    },
    clear: function(key) {
        if (this.isLS) window.localStorage.clear();
    }
}

/*
 * 获取URL参数
 */
bottlecms.getUrlSearch = function(name) {
    var searchstr = window.location.search.substr(1);
    if(name){
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
        var r = searchstr.match(reg); 
        if (r != null) return unescape(r[2]); 
        return null;
    }
    return searchstr;
}
/*
 * 获取URL参数
 */
bottlecms.getUrlHash = function(name) {
    var hashstr = window.location.hash.substr(1);
    if(name){
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
        var r = hashstr.match(reg); 
        if (r != null) return unescape(r[2]); 
        return null;
    }
    return hashstr;
}

/*
 * url字符串添加参数
 */
bottlecms.urlAddParam = function(url, paramName, replaceWith) {
    if (url.indexOf(paramName) > -1) {
        var re = eval('/(' + paramName + '=)([^&]*)/gi');
        url = url.replace(re, paramName + '=' + replaceWith);
    } else {
        var paraStr = paramName + '=' + replaceWith;

        var idx = url.indexOf('?');
        if (idx < 0)
            url += '?';
        else if (idx >= 0 && idx != url.length - 1)
            url += '&';
        url=url + paraStr;
    }
    return url;
};

/**
 * 复制
 */
bottlecms.copy = function (id) {
    let target = document.querySelector('#' + id);
    try {
        let range = document.createRange();
        range.selectNode(target);
        window.getSelection().removeAllRanges();
        window.getSelection().addRange(range);
        document.execCommand('copy');
        window.getSelection().removeAllRanges();
        console.log('复制成功')
        bottlecms.toast("复制成功");
    } catch (e) {
        console.log('复制失败')
        bottlecms.toast("复制失败");
    }
}

/*
 * 异步加载js
 */
bottlecms.getJs = function(src, callback) {
  
        if (document.querySelector("script[src='" + src + "']")) {
            return callback();
        }
        var x = document.getElementById('javascript-bottlecms-page');
        var js = document.createElement("script");
        js.src = src;
        js.type = 'text/javascript';
        js.async = true;
        js.defer = true;
        x.parentNode.insertBefore(js, x);
        js.onload = function() {
            callback();
        }
  
}
bottlecms.getJsArr = function(srcs, rfun) {
    var num = srcs.length;
    for (var o in srcs) {
        bottlecms.getJs(srcs[o], function() {
            if (num > 1) {
                num--;
            } else {
                if (rfun) return rfun();
            }
        });
    }
}
/**
 * 毫秒时间戳
 */
bottlecms.microtime = function(flag, date) {
    try {
        if (!flag && !date) return new Date().getTime();
        if (flag && !date) {
            return new Date(flag.replace(/-/g, '/')).getTime();
        }
        if (!date) return "";
        var da = new Date(bottlecms.parseInt(date));
        var Y = da.getFullYear(),
            m = da.getMonth() + 1,
            d = da.getDate(),
            H = da.getHours(),
            i = da.getMinutes(),
            s = da.getSeconds(),
            x = da.getMilliseconds();
        return flag.replace("Y", Y).replace("m", (m < 10 ? "0" + m : m)).replace("d", (d < 10 ? "0" + d : d)).replace("H", (H < 10 ? "0" + H : H)).replace("i", (i < 10 ? "0" + i : i)).replace("s", (s < 10 ? "0" + s : s)).replace("x", x);
    } catch (err) {
        return "";
    }
}
/**
 * 时间格式化
 */
bottlecms.dateformat = function(flag, str) {
    try {
        str = str.replace(/-/g, '/'); // 将-替换成/，因为下面这个构造函数只支持/分隔的日期字符串
        var date = new Date(str);
        var time = date.getTime();
        return bottlecms.microtime(flag, time);
    } catch (err) {
        return "";
    }
}
/**
 *日期格式转换几天前,几小时前，几分钟前
 */
bottlecms.getDateDiff = function(dateTimeStamp) {
    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var halfamonth = day * 15;
    var month = day * 30;
    var now = new Date().getTime();
    var diffValue = now - dateTimeStamp;
    if (diffValue < 0) {
        return;
    }
    var monthC = diffValue / month;
    var weekC = diffValue / (7 * day);
    var dayC = diffValue / day;
    var hourC = diffValue / hour;
    var minC = diffValue / minute;
    if (monthC >= 1) {
        //result="" + bottlecms.parseInt(monthC) + "月前";
        result = bottlecms.microtime('m-d H:i', dateTimeStamp)
    } else if (weekC >= 1) {
        //result="" + bottlecms.parseInt(weekC) + "周前";
        result = bottlecms.microtime('m-d H:i', dateTimeStamp)
    } else if (dayC >= 1) {
        result = "" + bottlecms.parseInt(dayC) + "天前";
    } else if (hourC >= 1) {
        result = "" + bottlecms.parseInt(hourC) + "小时前";
    } else if (minC >= 1) {
        result = "" + bottlecms.parseInt(minC) + "分钟前";
    } else result = "刚刚";
    return result;
}
/**
 * 转换货币格式
 */
bottlecms.centToYuan = function(num) {
    num = num ? num / 100 : 0;
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num)) num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10) cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
    return (((sign) ? '' : '-') + num + '.' + cents);
}
/**
 * pop弹窗
 */
bottlecms.modal = function(paras) {
    var bcpop = $('<div class="bcui_pop '+(paras.class||'')+'">' + paras.content + '</div>');
    var mask = $('<div class="bcui_mask"></div>');
    $('body').append(mask);
    $('body').append(bcpop);
    var duration = 300;
    mask.show().animate({
        opacity: paras.mask_opacity || .5
    }, {
        duration: duration
    });
    if (paras.popcss) {
        bcpop.css(paras.popcss);
    }

    var acss = {};
    if (paras.type == "left") {
        // 居左
        bcpop.show().css('left', -bottlecms.parseInt(bcpop.width())).css({
            top: 0,
            bottom: 0
        });
        bcpop.animate({
            left: 0,
        }, {
            duration: duration,
        });
        acss = {
            left: -bottlecms.parseInt(bcpop.width())
        }
    } else if (paras.type == "right") {
        // 居右
        bcpop.show().css('right', -bottlecms.parseInt(bcpop.width())).css({
            top: 0,
            bottom: 0
        });
        bcpop.animate({
            right: 0,
        }, {
            duration: duration,
        });
        acss = {
            right: -bottlecms.parseInt(bcpop.width())
        }
    } else if (paras.type == "bottom") {
        // 居下
        bcpop.show().css('bottom', -bottlecms.parseInt(bcpop.height())).css({
            left: 0,
            right: 0
        });
        bcpop.animate({
            bottom: 0,
        }, {
            duration: duration,
        });
        acss = {
            bottom: -bottlecms.parseInt(bcpop.height())
        }
    } else {
        //居中
        var height2 = -bottlecms.parseInt(bcpop.height() / 2);
        bcpop.show().css({
            'left': '50%',
            'top': '50%',
            'margin-left': -bottlecms.parseInt(bcpop.width() / 2),
            'margin-top': height2 - 20
        });
        bcpop.animate({
            marginTop: height2,
        }, {
            duration: duration,
        });
        acss = {
            marginTop: height2 - 20
        }
    }
    // 关闭
    var close = function() {
        bcpop.animate(acss, {
            duration: duration,
            complete: function() {
                bcpop.remove();
            }
        });
        mask.fadeOut(duration, function() {
            mask.remove();
        });
    }
    mask.click(function() {
        close();
    });
    $(bcpop).find('.close-pop').click(function(event) {
        close();
    });
    return {
        close: close,
        thispop: bcpop
    };
}
bottlecms.closeModal = function(){
    var bcpop = $('.bcui_pop');
    var mask = $('.bcui_mask');
    bcpop.animate(acss, {
        duration: 400,
        complete: function() {
            bcpop.remove();
        }
    });
    mask.fadeOut(400, function() {
        mask.remove();
    });
}

/**
 * 吐司
 */
bottlecms.toast = function(content, outtime) {
    var bcpop = $('<div class="bcui_toast"><div class="bcui_toast_main">' + content + '</div></div>');
    $('body').append(bcpop);
    bcpop.show().css('left', bottlecms.parseInt((window.innerWidth - bcpop.width()) / 2));
    bcpop.animate({
        bottom: 100
    }, {
        duration: 50
    }).animate({
        bottom: 95
    }, {
        duration: 150
    });
    setTimeout(function() {
        bcpop.animate({
            opacity: 0
        }, {
            duration: 100,
            complete: function() {
                bcpop.remove();
            }
        });
    }, outtime || 2000);
}
/**
 * 确认框
 */
bottlecms.confirm = function(content, complete, fail, paras) {
    paras = paras || [];
    var bcpop = $('<div class="bcui_confirm"><div class="bcui_confirm_coutent">' + content + '</div></div>');
    var mask = $('<div class="bcui_confirm_mask"></div>');
    var bbtn = $('<div class="bcui_confirm_btn" style=""></div>');
    var bconfirm = $('<a class="bcui_confirm_confirm">' + (paras.confirm_text || "确认") + '</a>');
    var bcancel = $('<a class="bcui_confirm_cancel">' + (paras.cancel_text || "取消") + '</a>');
    bbtn.append(bconfirm);
    if (paras.cancel != false) {
        bbtn.append(bcancel);
    } else {
        bconfirm.css('width', '100%');
    }
    bcpop.append(bbtn);
    $('body').append(mask);
    $('body').append(bcpop);
    mask.show().animate({
        opacity: .5
    }, {
        duration: 400
    });
    var height2 = -bottlecms.parseInt(bcpop.height() / 2);
    bcpop.show().css({
        'left': '50%',
        'top': '50%',
        'margin-left': -bottlecms.parseInt(bcpop.width() / 2),
        'margin-top': height2 - 20
    });
    bcpop.animate({
        marginTop: height2,
    }, {
        duration: 400,
    });
    // 关闭
    var pop_close = function() {
        try {
            bcpop.animate({
                marginTop: height2 - 20
            }, {
                duration: 400,
                complete: function() {
                    bcpop.remove();
                }
            });
            mask.fadeOut(400, function() {
                mask.remove();
            });
        } catch (err) {
            return false;
        }
    }
    bcancel.click(function() {
        if (fail) {
            if (paras.failselfclos != false) {
                pop_close();
            }
            fail(function() {
                pop_close();
            });
        } else {
            pop_close();
        }
    });
    bconfirm.click(function() {
        if (complete) {
            if (paras.comselfclos != false) {
                pop_close();
            }
            complete(bcpop,function() {
                pop_close();
            });
        } else {
            pop_close();
        }
    });
    return {
        close: pop_close,
        bcpop:bcpop
    };
}
/**
 * 警示框
 */
bottlecms.alert = function(content, complete, paras) {
    paras = paras || [];
    paras.cancel = false;
    this.confirm(content, complete, paras);
}
/**
 * 加载框
 */
bottlecms.loading = function(content, paras) {
    paras = paras || [];
    $(".bcui_loading_mask,.bcui_loading").remove();
    var html = "";
    if (paras.icon != false) html += '<div class="load-icon"></div>';
    if (content) html += '<div class="bcui_loading-title">' + content + '</div>';
    var bcpop = $('<div class="bcui_loading"><div class="bcui_loading_main">' + html + '</div></div>');
    var mask = $('<div class="bcui_loading_mask"></div>');
    $('body').append(mask);
    $('body').append(bcpop);
    
    mask.show().animate({
        opacity: paras.mask_opacity || .4
    }, {
        duration: 400
    });
    bcpop.show().css({
        'left': '50%',
        'top': '50%',
        'margin-left': -bottlecms.parseInt(bcpop.width() / 2),
        'margin-top': -bottlecms.parseInt(bcpop.height() / 2)
    });

    var close = function() {
        try {
            bcpop.remove();
            mask.remove();
        } catch (err) {
            return false;
        }
    }
    return {
        close: close,
        cont: function(con) {
            bcpop.find(".bcui_loading-title").html(con);
        }
    };
}

/**
 * pop弹窗
 */
bottlecms.actions = function(paras) {
    $(".bcui_actions_mask,.bcui_actions").remove();
    var bcpop = $('<div class="bcui_actions"></div>');
    var mask = $('<div class="bcui_actions_mask"></div>');
    var html ="";
    for (var o in paras) {
        html+='<div class="group">';
        for (var g in paras[o]) {
            html+='<div class="item bg-'+paras[o][g].bg+'">'+paras[o][g].text+'</div>';
        }
        html+='</div>';
    }
    bcpop.append(html);

    $('body').append(bcpop);
    $('body').append(mask);
    mask.show().animate({
        opacity:.5
    }, {
        duration: 300
    });

    var acss = {};
    bcpop.show().css('bottom', -bottlecms.parseInt(bcpop.height())).css({
        left: 0,
        right: 0
    });
    bcpop.animate({
        bottom: 0,
    }, {
        duration: 300,
    });
    acss = {
        bottom: -bottlecms.parseInt(bcpop.height())
    }
    
    // 关闭
    var close = function() {
        bcpop.animate(acss, {
            duration: 200,
            complete: function() {
                bcpop.remove();
            }
        });
        mask.fadeOut(200, function() {
            mask.remove();
        });
    }
    mask.click(function() {
        close();
    });

    var groups = bcpop.find('.group');
    groups.each(function (index, el) {
        var groupIndex = index;
        $(el).children().each(function (index, el) {
            var buttonIndex = index;
            var buttonParams = paras[groupIndex][buttonIndex];
            var clickTarget;
            if ($(el).is(".item")) clickTarget = $(el);

            if (clickTarget) {
                clickTarget.on('click', function (e) {
                    if (buttonParams.close !== false) close();
                    if (buttonParams.onClick) buttonParams.onClick(bcpop, e);
                });
            }
        });
    });

    return {
        close: close,
        thispop: bcpop
    };
}


/**
 * 跳转url 
 */
bottlecms.goto = function(url) {
    window.location.href = url;
}
/**
 * 返回 
 */
bottlecms.back = function() {
    bottlecms.goBack();
}
bottlecms.goBack = function() {
    try {
        if ((navigator.userAgent.indexOf('MSIE') >= 0) && (navigator.userAgent.indexOf('Opera') < 0)) { // IE
            if (history.length > 0) {
                window.history.go(-1);
            } else {
                window.location.href = "/";
            }
        } else { //非IE浏览器
            if (navigator.userAgent.indexOf('Firefox') >= 0 || navigator.userAgent.indexOf('Opera') >= 0 || navigator.userAgent.indexOf('Safari') >= 0 || navigator.userAgent.indexOf('Chrome') >= 0 || navigator.userAgent.indexOf('WebKit') >= 0) {
                if (window.history.length > 1) {
                    window.history.go(-1);
                } else {
                    window.location.href = "/";
                }
            } else { //未知的浏览器
                window.history.go(-1);
            }
        }
    } catch (err) {
        return errlog(err);
    }
}
// 不记录跳转
bottlecms.goReplace = function(href) {
    if (href && /^#|javasc/.test(href) === false) {
        if (history.replaceState) {
            history.replaceState(null, document.title, href.split('#')[0] + '#');
            location.replace('');
        } else {
            location.replace(href);
        }
    }
};

/**
 * ajax 
 */
bottlecms.ajax = function(url, jsobject, successfun, errorfun, opetions) {
    try {
        jsobject = jsobject || {};
        opetions = opetions || {};
        var option = {
            data: jsobject,
            type: "POST",
            url: url,
            dataType: "json",
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                'BOTTLECMS-ISAJAX': "true",
                'X-Requested-With': 'XMLHttpRequest'
            },
            success: function(response) {
                // bottlecms.log(response);
                if (response) {
                    if (response.code == 301 && response.obj) {
                        if (response.msg) bottlecms.toast(response.msg);
                        setTimeout(function() {
                            return bottlecms.goto(response.obj)
                        }, 1000)
                        return false;
                    }
                    if (response.code == 302) {
                        if (response.msg) bottlecms.toast(response.msg);
                        setTimeout(function() {
                            return bottlecms.back()
                        }, 1000)
                    }
                    if (response.code == 303 && response.obj) {
                        if (response.msg) bottlecms.toast(response.msg);
                        setTimeout(function() {
                            return window.location.href = response.obj;
                        }, 1000)
                    }
                }
                if (successfun) {
                    return successfun(response)
                }
            },
            error: function(obj, errmsg) {
                bottlecms.log(obj);
                if (errorfun) {
                    errorfun(obj);
                } else {
                    if (obj.status == 422) {
                        var rdata = JSON.parse(obj.responseText);
                        for (var o in rdata) {
                            return bottlecms.toast(rdata[o][0]);
                        }
                    }
                    bottlecms.toast("网络错误");
                }
            }
        };
        if (errorfun === false) {
            option.async = false;
        }
        // bottlecms.log(opetions)
        if (opetions) {
            for (var o in opetions) {
                option[o] = opetions[o];
            }
            if (option['type'] && option['type'] != 'GET' && option['type'] != 'POST') {
                jsobject['_method'] = option['type'];
                option['jsobject'] = jsobject;
                option['type'] = "POST";
            }
        }
        // bottlecms.log(option)
        $.ajax(option);
    } catch (err) {
        return errlog("ajax:"+err);
    }
}
/**
 * ajax.get
 */
bottlecms.get = function(url, jsobject, successfun, errorfun, opetions) {
    opetions = opetions || [];
    opetions.type = "GET";
    return this.ajax(url, jsobject, successfun, errorfun, opetions);
}
/**
 * ajax.post
 */
bottlecms.post = function(url, jsobject, successfun, errorfun, opetions) {
    opetions = opetions || [];
    opetions.type = "POST";
    return this.ajax(url, jsobject, successfun, errorfun, opetions);
}
/**
 * ajax.put
 */
bottlecms.put = function(url, jsobject, successfun, errorfun, opetions) {
    opetions = opetions || [];
    opetions.type = "PUT";
    return this.ajax(url, jsobject, successfun, errorfun, opetions);
}
/**
 * ajax.delete
 */
bottlecms.delete = function(url, jsobject, successfun, errorfun, opetions) {
    opetions = opetions || [];
    opetions.type = "DELETE";
    return this.ajax(url, jsobject, successfun, errorfun, opetions);
}
bottlecms.getScript = function(url, successfun) {
    var opetions = [];
    opetions.dataType = "script";
    return this.get(url, null, successfun, null, opetions);
}
bottlecms.getStyle = function(url, successfun) {
    var styleTag = document.createElement("link");
    styleTag.setAttribute('type', 'text/css');
    styleTag.setAttribute('rel', 'stylesheet');
    styleTag.setAttribute('href', url);
    $("head")[0].appendChild(styleTag);
}
/**
 * 流加载 
 * @paras.elem string //指定列表容器
 * @paras.scrollElem string //滚动条所在元素选择器，默认document。
 * @paras.scroll boole //是否开启上拉自动加载默认
 * @paras.distance number //与底部的临界距离，默认100
 */
bottlecms.load = function(paras) {
    var _page = $(".page");
    var elem_target = paras.elem || $(_page).find('.bcui-infinite');
    var preloader_target = elem_target.find(".bcui-infinite-preloader");
    var list_target = elem_target.find(".bcui-infinite-list");
    var infinite_scroll = paras.scroll || $(_page).find('.infinite-scroll');
    var limit = elem_target.attr('limit') || 10;
    var distance = paras.distance || 1000;
    var isinfiniteon = paras.isinfiniteon;
    var isinfinite = paras.isinfinite;
    // 页数
    var page = elem_target.attr('page') || 1;
    // 加载flag
    var loading = false;
    var load = function() {
        if (loading) return;
        loading = true;
        preloader_target.attr('status', "loading");
        setTimeout(function() {
            paras.done(page, function(lisdata, item_count) {
                if (page <= 1) {
                    list_target.html("")
                }
                // 添加新条目
                if (lisdata) {
                    list_target.append(lisdata);
                    preloader_target.attr('status', "more");
                    loading = false;
                    page++;
                    elem_target.attr('page', page);
                }
                //没有数据
                if (page < 2 && item_count < 1) {
                    preloader_target.attr('status', "nothing");
                    return;
                }
                // 没有了
                if (!item_count || item_count < limit) {
                    preloader_target.attr('status', "end");
                    return;
                }
            })
        }, 100)
    }
    // 注册'scroll'事件处理函数
    if (isinfinite !== false) {
        $(infinite_scroll).scroll(function() {
            if (($(this).scrollTop() + $(this).height() + distance) > $(elem_target).height()) {
                if (isinfiniteon !== false) {
                    load();
                }
            }
        });
    }
    // 点击加载更多按钮
    preloader_target.find('.bcui-flow-more').click(function(event) {
        load();
    });
    // 初始化
    var init = function() {
        if (page < 2) {
            load();
        }
    }
    // 刷新
    var refresh = function() {
        loading = false;
        preloader_target.attr('status', "more");
        page = 1;
        elem_target.attr('page', "1");
        list_target.html("");
        load();
    }
    return {
        init: init,
        load: load,
        refresh: refresh
    }
}


/**
 * selcet 联动
 * @returns
 */
function BOTTLECMS_getnextsel(o, tn, aw) {
    var val = $(o).val();
    if (val instanceof Array) val = val[0]
    if (val == $(o).data('lastval')) {
        return;
    }
    var uuid = $(o).attr('seluuid');
    var index = parseInt($(o).attr('selindex'));
    var sel = $('select[seluuid="' + uuid + '"]');
    sel.each(function() {
        var ind = parseInt($(this).attr('selindex'));
        if (ind <= index) {
            sel = sel.not($(this));
            return;
        }
        $(this).find('option').each(function(i) {
            if (i > 0) {
                $(this).remove();
            }
        });
    });
    $(o).data('lastval', val);
    if (bottlecms.trim(val) != '') {
        bottlecms.ajax(BOTTLECMS_ROOT_PATH + 'getselvt/' + tn + '/' + val, null, function(m) {
            var m = m.list;
            if (m && m.length > 2) {
                sel.eq(0).show();
                for (var i = 0; i < m.length; i++) {
                    sel.eq(0).append('<option value="' + m[i].id + '">' + m[i].name + '</option>');
                }
            } else {
                sel.eq(0).hide();
            }
        }, null, {
            type: "GET"
        });
    }
}




/**
 * tab 选项卡
 * @
 */ 
if ($(".bcui-tab").length > 0) {

    var changetab = function(_this){
        var tab = $(_this).parents(".bcui-tab");
        var n = tab.find(".bcui-tab-title>.item").index(_this);
        $(_this).addClass('active').siblings().removeClass('active');
        tab.find('.bcui-tab-content>.item').removeClass('active').eq(n).addClass('active');
    }
    $(".bcui-tab .bcui-tab-title>.item").click(function(event) {
        // if($(this).attr('tab')){
        //     window.location.href = "#tab="+$(this).attr('tab');
        // }else{
        //     changetab(this);
        // }
        changetab(this);
    });

    var gettabitem = function(){
        var tab = bottlecms.getUrlHash('tab');
        var item = $(".bcui-tab .bcui-tab-title>.item[tab='"+tab+"']");
        if(item.length<1){
            item = $(".bcui-tab .bcui-tab-title>.item.active");
        }
        if(item.length<1){
            item = $(".bcui-tab .bcui-tab-title>.item").eq(0);
        }
        changetab(item);
    }

    gettabitem();
    window.onhashchange = gettabitem;
    
    if ($(".bcui-tab-title-float").length > 0) {
        $(document).ready(function() {
            $(".page-content").scroll(function() {
                var tittop = bottlecms.parseInt($(".bcui-tab-title-float").offset().top);
                var qthei = bottlecms.parseInt($('.head-nav-wrap').height());
                if ((tittop- qthei) < 0) {
                    $(".bcui-tab-title-float").addClass('fixed');
                } else {
                    $(".bcui-tab-title-float").removeClass('fixed');
                }
            }).trigger("scroll");
        });
    }
}

/**
 * from转ajax提交
 * @
 */
$(document).on('submit', "form[bottlecms-form-ajax]", function(event) {
    event.preventDefault();
    var _this = this;
    var ajax_url = $(_this).attr("action");
    var ajax_data = $(_this).serialize();
    var confirm_title = $(_this).attr('confirm-title');
    var confirm_text = $(_this).attr('confirm-text');

    var target = function(){
        var target = $(_this).attr('target');
        if(target){
            if(target=="back"){
                return bottlecms.back();
            }else if(target=="refresh"){
                return window.location.href = window.location.href;
            }else{
                return window.location.href = target;
            }
        }
        return window.location.href = window.location.href;
    }

    if (confirm_title || confirm_text) {
        bottlecms.confirm(confirm_title+confirm_text, function() {
            bottlecms.post(ajax_url, ajax_data, function(data) {
                if (data.success == true) {
                    if (data.msg) bottlecms.toast(data.msg);
                    setTimeout(function() {
                        return target();
                    }, 1000)
                } else {
                    if (data.msg) bottlecms.toast(data.msg)
                }
            });
        })
        return;
    }
    bottlecms.post(ajax_url, ajax_data, function(data) {
        if (data.success == true) {
            if (data.msg) bottlecms.toast(data.msg);
            setTimeout(function() {
                return target();
            }, 1000)
        } else {
            if (data.msg) bottlecms.toast(data.msg)
        }
    });
});





/**
 * 文件上传 
 */
bottlecms.uploadfile = function(options) {
    options = options || [];

    var elem = options.elem;
    var maxsize = options.maxsize || 20;
    var url = options.url || "/m/ajax/common/upload?filedir="+$("#filedir").val();

    var file = elem.files[0];
    if (file.size > (maxsize*1024*1024)) { 
        return bottlecms.toast("最大"+maxsize+"M");
    }
    // if (file.type) { 
    //     return bottlecms.toast("文件类型错误");
    // }


    var form_data = new FormData(); 
    form_data.append("file", file); 

    if(options.data){
        for(var o in options.data){
            form_data.append(o, options.data[o]); 
        }
    }
    var loadingobj;
    if(options.loading !=false){
       loadingobj = bottlecms.loading('上传中…'); 
    }
    bottlecms.ajax(url,form_data,function(rdata){
        if (rdata.success == true && rdata.obj) {
            options.success && options.success(rdata.obj);
        }else{
            bottlecms.toast(rdata.msg);
        }
    },function(rerr){
        bottlecms.toast(rdata.msg);
        options.error && options.error(msg);
    },{
        type: "POST",
        dataType : "json",
        cache: false,
        processData: false, 
        contentType: false,
        complete:function(e){
            if(options.loading !=false){
                loadingobj.close();
            }
        }
    })
}
// $(document).on('change', "input[type='file'][bcui-upload-input]", function(event) {
//     event.preventDefault();
//     var options = $(this).data();
//     bottlecms.uploadfile({
//         elem:this,
//         data:options,
//         success:function(data){
//             if (options.function) eval(options.function+"('" + data + "')");
//         }
//     })
// });


/**
 * 文件上传
 */
bottlecms.layuiuploadfile = function(options) {
    options = options || [];
    var elem = options.elem;
    var accept = (options.accept || "images");
    var maxsize = options.maxsize || 50*1024;
    var filedir= $("#filedir").val();
    if (options.filedir!=undefined && options.filedir!=""){
        filedir=options.filedir;
    }
    var url = options.url || "/m/ajax/common/upload?filedir="+filedir;

    layui.upload.render({
        elem: elem
        ,url: url
        ,field:'file'
        // ,multiple:false //是否允许多文件上传
        ,auto:true//是否选完文件后自动上传
        ,headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
        ,accept: accept //允许上传的文件类型:images、file（所有文件）、video、audio
        ,size: maxsize //最大允许上传的文件大小
        //,acceptMime:'image/*' //打开文件选择框时，筛选出的文件类型
        // ,before: function(obj){
        //   //预读本地文件示例，不支持ie8
        //   obj.preview(function(index, file, result){
        //     $('#demo1').attr('src', result); //图片链接（base64）
        //   });
        // }
        ,done: function(rdata){
            if (rdata.success == true && rdata.obj) {
                options.success && options.success(rdata.obj);
            }else{
                bottlecms.toast(rdata.msg);
            }
        }
        ,error: function(){
            bottlecms.toast(rdata.msg);
            options.error && options.error(msg);
        }
    });
}

/**
 * audio
 * @
 */
$(document).on('click', ".bcui_voice", function(event) {
    // debugger;
    event.preventDefault();
    event.stopPropagation();
    var _this = this;
    var voice_id = $(this).find('audio').attr('id');
    var audio = document.getElementById(voice_id);
    if (audio !== null) {
        if (audio.paused) {
            $(document).find('.bcui_voice.play').click();
            audio.play();
            $(_this).addClass('play');
        } else {
            audio.pause();
            $(_this).removeClass('play');
        }
        audio.addEventListener("ended", function() {
            $(_this).removeClass('play');
            audio.pause();
        }, false);
    }
});
/**
 * head-filter
 */
$(function() {
    if ($('.head-filter').length > 0) {
        $(".head-filter").after('<div class="head-filter-mask"></div>');
        $('.head-filter-mask').on('click', function() {
            $(".head-filter .head-filter-item").removeClass('active');
            $(this).hide();
        });
        $('.head-filter .head-filter-title').on('click', function() {
            if ($(this).parent(".head-filter-item").hasClass('active')) {
                $('.head-filter-mask').click();
            } else {
                $('.head-filter-mask').show();
                $(this).parents(".head-filter").find(".head-filter-item").removeClass('active');
                $(this).parent(".head-filter-item").addClass('active');
            }
        })
    }
});

/**
 * long_press
 */
bottlecms.long_press = function(_page, object, lrun, drun, duration) {
    try {
        var time;
        var timer;
        duration = duration || 2;
        var _this;
        var istrue = true;
        $(_page).on('touchstart mousedown', object, function(event) {
            // event.preventDefault();
            // event.stopPropagation();
            istrue = true;
            clearInterval(timer);
            _this = this;
            // $(_this).addClass('active');
            time = 0;
            timer = setInterval(function() {
                if (time > duration) {
                    if (istrue != true) {
                        return;
                    }
                    clearInterval(timer);
                    // $(_this).addClass('longpress');
                    return lrun(_this);
                }
                time++;
            }, 100);
        }).on('touchmove', function(e) {
            time = 0;
            istrue = false;
            clearInterval(timer);
        }).on('touchend touchcancel mouseup', function(e) {
            clearInterval(timer);
            // $(_this).removeClass('active');
            if (time <= duration) {
                if (istrue != true) {
                    return;
                }
                return drun(_this);
            }
        });
    } catch (err) {
        return errlog(err);
    }
}


/**
 * 图片预览
 * @
 */
bottlecms.photoBrowser = function(options){
    var p = this;
    var option = [];
    if (options) {
        for (var o in options) {
            option[o] = options[o];
        }
    }
    p.init = function(){
        if($(".bcui-pswp").length>0){
            elem = $(".bcui-pswp");
        }else{
            var elem = $('<div aria-hidden="true" class="pswp bcui-pswp" role="dialog" tabindex="-1"><div class="pswp__bg"></div><div class="pswp__scroll-wrap"><div class="pswp__container"><div class="pswp__item"></div><div class="pswp__item"></div><div class="pswp__item"></div></div><div class="pswp__ui pswp__ui--hidden"><div class="pswp__top-bar"><div class="pswp__counter"></div><button class="pswp__button pswp__button--close" title="关闭"></button><button class="pswp__button pswp__button--zoom" title="放大/缩小"></button><div class="pswp__preloader"><div class="pswp__preloader__icn"><div class="pswp__preloader__cut"><div class="pswp__preloader__donut"></div></div></div></div></div><div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap"><div class="pswp__share-tooltip"></div></div><button class="pswp__button pswp__button--arrow--left" title="上一个"></button><button class="pswp__button pswp__button--arrow--right" title="下一个"></button><div class="pswp__caption"><div class="pswp__caption__center"></div></div></div></div></div>');
            $('body').append(elem);
        }
        p.elem = elem;
    }
    p.init();
    p.open = function(index){
        var gallery = new PhotoSwipe($(p.elem)[0], PhotoSwipeUI_Default, option.photos,
                    {
                        loop:false,
                        history:false,
                        index:index
                    });
        gallery.init();
    }
    return p;
}





function toCamel(str) {
    return str.replace(/([^_])(?:_+([^_]))/g, function ($0, $1, $2) {
        return $1 + $2.toUpperCase();
    });
}
/**
 * 轮播图
 * @
 */
$('.bcui-carousel').each(function(index, el) {
    var datas = $(this).data();
    var newdata = {};
    for(var o in datas){
        newdata[toCamel(o)] = datas[o];
    }
    $(this).swipeslider(newdata);
});





bottlecms.openPanel = function(target){
    $(target).css({display: 'block'}).addClass('active');
    $("body").toggleClass('with-panel-right-reveal');
}

bottlecms.closePanel = function(){
    $('body').addClass('panel-closing').removeClass('with-panel-right-reveal');
    $(".panel").removeClass('active').hide();

    setTimeout(()=>{
        $('body').removeClass('panel-closing');
    },300)
}
$(document).on("click","[data-panel]",function(e){
    bottlecms.openPanel($(this).attr("data-panel"));
})
$(document).on("click",".panel-overlay",function(e){
    bottlecms.closePanel();
})


$(document).on("click","[data-toggle]",function(e){
    $('.'+$(this).attr("data-toggle")).toggleClass('activate');
})



$(document).ready(function($) {
    if ($('[bc-lazy-img]').length > 0) {
        $('[bc-lazy-img]').each(function(index, el) {
            $(this).attr('src', $(this).attr('bc-lazy-img'));
        });
    }
    if ($('[bc-lazy-back]').length > 0) {
        $('[bc-lazy-back]').each(function(index, el) {
            $(this).css('background-image', "url(" + $(this).attr('bc-lazy-back') + ")");
        });
    }
});


// 阻止长按菜单
// document.body.addEventListener('contextmenu', function(e){
//         e.preventDefault();
//       });
! function(e) {
    function o(s) {
        if (t[s]) return t[s].exports;
        var n = t[s] = {
            exports: {},
            id: s,
            loaded: !1
        };
        return e[s].call(n.exports, n, n.exports, o), n.loaded = !0, n.exports
    }
    var t = {};
    return o.m = e, o.c = t, o.p = "", o(0)
}([function(e, o, t) {
    e.exports = t(1)
}, function(e, o) {
    ! function() {
        var e;
        if (window.console && "undefined" != typeof console.log) {
            try {
                (window.parent.__has_console_security_message || window.top.__has_console_security_message) && (e = !0)
            } catch (o) {
                e = !0
            }
            if (window.__has_console_security_message || e) return;
            var t = "",
                s = "^_^ \u505a\u5730\u7403\u4e0a\u6700\u5177\u4e92\u8054\u7f51\u6027\u3001\u521b\u65b0\u6027\u3001\u4e13\u4e1a\u6709\u7231\u7684\u56e2\u961f\u3002",
                n = "http://www.xiats.com",
                i = [s, " ", n].join("");
            /msie/gi.test(navigator.userAgent) ? (console.log(i)) : (console.log("%c xiats.com %c Copyright \xa9 2020-%s", 'font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;font-size:64px;color:#F149A2;-webkit-text-fill-color:#F149A2;-webkit-text-stroke: 1px #F149A2;', "font-size:12px;color:#999999;", (new Date).getFullYear()), console.log("\n " + i)), window.__has_console_security_message = !0
        }
    }()
}]);

// ios手机上失焦回弹(软键盘收起 底部空白问题)
$(document).on('blur', 'input[type=text],input[type=number],input[type=tel],input[type=password],textarea', function(event) {
    event.preventDefault();
    if (!!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
        setTimeout(() => {
            window.scrollTo(0, 0)
        }, 100)
    }
});

$(document).on('submit', "form", function(event) {
    $(this).find('input').blur();
});

var isWechat = function(){
    return /MicroMessenger/.test(window.navigator.userAgent) ? true :false;
}


function bc_static(file){
    return BOTTLECMS_STATIC+file;
}

function nofind_img(){
    var img=event.srcElement;
    img.src="/m/img/recruit_tx.png";
    img.οnerrοr=null;
}